﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Rabbit.API.Application.Command.Goods;
using System.Collections.Generic;

namespace Rabbit.API.Application.Handler.Goods
{
    public class GoodsGetAllDataHandler:IRequestHandler<GoodsGetAllDataCommand,APIResult<List<GoodsModel>>>
    {
        private readonly IRepository<GoodsModel> goodsway;
        private readonly IMapper mapper;
        private readonly ILogger<GoodsGetHandler> log;

        public GoodsGetAllDataHandler(IRepository<GoodsModel> goodsway, IMapper mapper, ILogger<GoodsGetHandler> log)
        {
            this.goodsway = goodsway;
            this.mapper = mapper;
            this.log = log;
        }
        /// <summary>
        /// 获取商品导出信息
        /// </summary>
        /// <param name="request">限制条数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>未删除的商品数据</returns>
        public Task<APIResult<List<GoodsModel>>> Handle(GoodsGetAllDataCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<GoodsModel>> res = new APIResult<List<GoodsModel>>();
            try
            {
                IQueryable<GoodsModel>? value = goodsway.GetAll().Where(x => x.IsDel == false);
                var result =value.Take(request.Limit).ToList();
              
                if(result!=null)
                {
                    log.LogInformation($"获取导出数据");
                    res.Message = "获取导出数据";
                    res.Num = StateCode.OK;
                    res.Data=result.ToList();
                }
                else
                {
                    log.LogError($"获取导出数据失败");
                    res.Message = "获取导出数据失败";
                    res.Num = StateCode.Fail;
                }
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                log.LogError($"获取导出数据时发生异常{ex.Message}");
                throw;
            }
        }
    }
}
